<template>
  <div class="content_box">
    <div class="time_box" v-if="msg.orderTotalState==1">
      <div class="box">
        订单已使用
        <div class="down">
          <van-count-down :auto-start="false" use-slot :time="msg.usedTime" @change="onChange1">
            <text class="item">{{ timeData1.hours }}<text class="mh">:</text></text>
            <text class="item">{{ timeData1.minutes }}<text class="mh">:</text></text>
            <text class="item">{{ timeData1.seconds }}</text>
          </van-count-down>
        </div>
      </div>
      <div class="box">
        还剩
        <div class="down">
          <van-count-down use-slot :time="msg.timeRemaining" @change="onChange">
            <text class="item">{{ timeData.hours }}<text class="mh">:</text></text>
            <text class="item">{{ timeData.minutes }}<text class="mh">:</text></text>
            <text class="item">{{ timeData.seconds }}</text>
          </van-count-down>
        </div>
      </div>
    </div>
    <div class="img_box" @click="previewImage(msg.roomImg)">
      <van-image
        width="100%"
        height="500rpx"
        fit="cover"
        lazy-load
        :src="msg.roomImg&&msg.roomImg.length?msg.roomImg[0]:''"
      />
      <div class="dots">
        <img mode="widthFix" src="/static/images/more_img.png" alt="" />
        {{msg.roomImg&&msg.roomImg.length?msg.roomImg.length:0}}
      </div>
    </div>
    <div class="room_msg">
      <div class="name_box">
        <p>{{msg.roomName}}（{{msg.roomTypeName}}）</p>
        <button open-type="share" v-if="shareType == '0' && msg.orderTotalState==1 || msg.orderTotalState==0">
          <img src="/static/images/share.png" alt="">
        </button>
        
      </div>
      <div class="msg_box">
        <div class="changeTime">
          <div class="left">
            <p class="text">开始时间</p>
            <p class="time">{{msg.startDate1}}</p>
            <p class="day">{{msg.startWeek}} {{msg.startSj}}</p>
          </div>
          <div class="center">
            <p class="totel">共{{msg.timeLength}}小时</p>
          </div>
          <div class="left">
            <p class="text">结束时间</p>
            <p class="time">{{msg.endDate1}}</p>
            <p class="day">{{msg.endWeek}} {{msg.endSj}}</p>
          </div>
        </div>
      </div>
    </div>
    <div class="cz_box">
     
      <div class="box" @click="kefuShow = true">
        <img src="/static/images/kefu1.png" alt="">
        <p class="text">联系客服</p>
      </div>
      <div class="box" @click="wifiShow = true">
        <img src="/static/images/wifi-fill.png" alt="">
        <p class="text">查看WIFI</p>
      </div>
      <div class="box" @click="openDoor(0)" v-if="msg.orderTotalState==1 || msg.orderTotalState==0">
        <img src="/static/images/dm.png" alt="">
        <p class="text">打开大门</p>
      </div>
      <div class="box" @click="openDoor(1)" v-if="msg.orderTotalState==1 || msg.orderTotalState==0">
        <img src="/static/images/fj.png" alt="">
        <p class="text">打开房间</p>
      </div>
    </div>
    <div class="order_msg" :style="{marginBottom:isIphoneXnum+'px'}">
      <div class="title_box">
        <p class="title">订单信息</p>
        <p class="status" v-if="msg.orderTotalState==1">使用中</p>
        <p class="status" v-else-if="msg.orderTotalState==0">已预约</p>
        <p class="status" v-else-if="msg.orderTotalState==2">已完成</p>
        <p class="status" v-else-if="msg.orderTotalState==3">已取消</p>
        <p class="status" v-else-if="msg.orderTotalState==4">待付款</p>
        <p class="status" v-else-if="msg.orderTotalState==5">正在付款</p>
        <p class="status" v-else-if="msg.orderTotalState==6">提前取消</p>
        <p class="status" v-else-if="msg.orderTotalState==7">提前结束</p>
        <p class="status" v-else-if="msg.orderTotalState==8">平台退款</p>
      </div>
      <div class="list_box">
        <div class="box">
          <p class="title">下单时间</p>
          <p class="text">{{msg.createTime}}</p>
        </div>
        <div class="box">
          <p class="title">订单金额</p>
          <p class="text">￥{{msg.realPrice}}</p>
        </div>
        <div class="box" v-if="msg.reorderPrice != '0.00'">
          <p class="title">续单金额</p>
          <p class="text">￥{{msg.reorderPrice}}</p>
        </div>
        <div class="box" v-if="msg.refundAmount != '0.00'">
          <p class="title">退款金额</p>
          <p class="text">￥{{msg.refundAmount}}</p>
        </div>
        <div class="box">
          <p class="title">支付方式</p>
          <p class="text">{{msg.payType == 1?'余额支付':msg.payType == 2?'美团验券':'微信支付'}}</p>
        </div>
        <div class="box">
          <p class="title">订单编号</p>
          <p class="text">{{msg.orderCode}}</p>
        </div>
        <div class="box">
          <p class="title">服务地址</p>
          <p class="text">{{msg.address}}</p>
        </div>
      </div>
    </div>
    <p style="height:1px"></p>

    <!-- wifi -->
    <div class="wifi_pop">
      <van-popup :show="wifiShow">
        <div class="box">
          <img class="bj" src="/static/images/wifi_pop.png" alt="">
          <div class="nr">
            <p class="title">共享WIFI</p>
            <p class="text">应许之地祝您娱乐愉快~</p>
            <div class="zhanghao">
              <p class="text1">WIFI 账号：{{msg.wifiName}}</p>
              <p class="text1">WIFI 密码：{{msg.wifiPassword}}</p>
            </div>
            <p class="anniu" @click="connectWifi">一键链接</p>
          </div>
        </div>
        <p class="close" @click="wifiShow = false"><van-icon name="cross" /></p>
      </van-popup>
    </div>

    <!-- 联系客服 -->
    <div class="kefu_pop">
      <van-popup position="bottom" :show="kefuShow" @close="kefuShow = false">
        <div class="box">
          <p class="title">联系客服</p>
          <div class="nr">
            <button type="primary" open-type="contact">
              <p class="img">
                <img src="/static/images/kefu.png" alt="">
              </p>
              <p class="text">在线客服</p>
            </button>
            <button @click="callPhone">
              <p class="img">
                <img src="/static/images/tell.png" alt="">
              </p>
              <p class="text">电话客服</p>
            </button>
          </div>
          <p class="quxiao" @click="kefuShow = false">取消</p>
        </div>
      </van-popup>
    </div>

    <block v-if="shareType == '0' && msg.payType!=2">
      <!-- 使用中 -->
      <div v-if="msg.orderTotalState==1" class="button_box" :style="{paddingBottom:isIphoneXnum+'px'}">
        <p @click="overOrder">离店&结束当前订单</p>
        <p class="xd" @click="toXudan">续单</p>
      </div>

      <!-- 预约中 -->
      <div v-if="msg.orderTotalState==0" class="button_box" :style="{paddingBottom:isIphoneXnum+'px'}">
        <p @click="cancelOrder" style="width:100%">取消订单</p>
        <!-- <p class="xd" @click="toXudan">续单</p> -->
      </div>
    </block>
  </div>
</template>

<script>
import { 
  getToken,
  getUserPhone
} from "@/utils/auth";
import { Debounce,minTime } from "@/utils"
import { 
  getMyOrderDetails,
  orderUnLock,
  startBack,
  endUse,
  unStoreLock
} from "@/api/index";
export default {
  data() {
    return {
      timeData: {},
      timeData1: {},
      msg:{
        usedTime:30 * 60 * 60 * 1000,
        timeRemaining:30 * 60 * 60 * 1000
      },
      isIphoneXnum:0,
      orderId:'',
      wifiShow:false,
      kefuShow:false,
      isOpen:false,
      shareType:0,// 0是正常进入，1是分享进入
    };
  },
  onShareAppMessage() {
    return {
      title: '我在老地方等你，速来~~',
      path: `/pages/order_xq/main?orderId=${this.msg.id}&shareType=1`,
      imageUrl:this.msg.roomImg[0]
    }
 },
  methods: {

    // 跳转续单
    toXudan(){
      if(!getUserPhone()){
        wx.navigateTo({
          url: '/pages/authorization/main',
        });
        return
      }
      let timeLength = this.getHour(this.msg.startTime,this.msg.endTime)
      
      let info = {
        endTime:this.msg.endTime,
        orderId:this.msg.id,
        price:this.msg.price,
        roomId:this.msg.roomId,
        roomName:this.msg.roomName,
        serviceTime:timeLength,
        startTime:this.msg.startTime
      }
      console.log(info)
      info.endTime = info.endTime.replace(/-/g, '/')
      info.startTime = info.startTime.replace(/-/g, '/')
      wx.navigateTo({
        url: `/pages/renewalOrder/main?info=${JSON.stringify(info)}`,
      });
    },

    // 提前结束订单
    overOrder(){
      if(!getUserPhone()){
        wx.navigateTo({
          url: '/pages/authorization/main',
        });
        return
      }
      const _this = this
      wx.showModal({
        title: '提示',
        content: '提前结束订单将扣除四小时最低消费后退回',
        success (res) {
          if (res.confirm) {
            _this.$showLoading('结束中...')
            endUse({orderId:_this.orderId}).then(res=>{
              if(res.statusCode == '00000'){
                if(res.data){
                  wx.hideLoading()
                  _this.$toast('订单已结束')
                  setTimeout(() => {
                    _this.getOrderMsg()
                  }, 800);
                }else{
                  wx.hideLoading()
                  _this.$toast('结束失败，请稍后再试')
                }
              }else{
                wx.hideLoading()
                _this.$toast(res.message)
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },

    // 取消订单
    cancelOrder(){
      if(!getUserPhone()){
        wx.navigateTo({
          url: '/pages/authorization/main',
        });
        return
      }
      const _this = this
      wx.showModal({
        title: '提示',
        content: '提前取消平台会依据房间预订详情中的相应条款收取费用，确认取消该订单？',
        success (res) {
          if (res.confirm) {
            _this.$showLoading('取消中...')
            startBack({orderId:_this.orderId}).then(res=>{
              if(res.statusCode == '00000'){
                if(res.data){
                  wx.hideLoading()
                  _this.getOrderMsg()
                  _this.$toast('订单已取消')
                }else{
                  wx.hideLoading()
                  _this.$toast('取消失败，请稍后再试')
                }
              }else{
                wx.hideLoading()
                _this.$toast(res.message)
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },

    // 开门
    openDoor:Debounce(function (num) {
      if(!getUserPhone()){
        wx.navigateTo({
          url: '/pages/authorization/main',
        });
        return
      }
      if(!this.isOpen){
        this.isOpen = true
        this.$showLoading('开门中...')
        let returnData = !num?unStoreLock({orderId:this.orderId}):orderUnLock({orderId:this.orderId})
        returnData.then(res=>{
          if(res.statusCode == '00000'){
            this.isOpen = false
            wx.hideLoading()
            this.$toast('开门成功')
          }else{
            this.isOpen = false
            wx.hideLoading()
            this.$toast(res.message)
          }
        })
        // orderUnLock({orderId:this.orderId}).then(res=>{
        //   if(res.statusCode == '00000'){
        //     wx.hideLoading()
        //     this.isOpen = false
        //     this.$toast('开门成功')
        //   }else{
        //     wx.hideLoading()
        //     this.$toast(res.message)
        //     this.isOpen = false
        //   }
        // })
      }
    },300),

    // 客服电话
    callPhone() {
      wx.makePhoneCall({
        phoneNumber: this.msg.mobile //仅为示例，并非真实的电话号码
      })
    },

    // 跳转意见反馈
    toFeedBack(){
      if(!getUserPhone()){
        wx.navigateTo({
          url: '/pages/authorization/main',
        });
        return
      }
      wx.navigateTo({
        url: `/pages/feedback/main`,
      });
    },

    // 一键链接wifi
    connectWifi() {
      var that = this;
      //检测手机型号
      wx.getSystemInfo({
        success:(res)=>{
          var system = '';
          if (res.platform == 'android') system = parseInt(res.system.substr(8));
          if (res.platform == 'ios') system = parseInt(res.system.substr(4));
          if (res.platform == 'android' && system < 6) {
              this.$toast('手机版本不支持~')
              return;
          }
          if (res.platform == 'ios' && system < 11.2) {
              this.$toast('手机版本不支持~')
              return;
          }
          //2.初始化 Wi-Fi 模块
          console.log("支持")
          that.startWifi();
        }
      });
    },

    //初始化 Wi-Fi 模块
    startWifi() {
      let that = this
      wx.startWifi({
        success: () =>{
          //请求成功连接Wifi
          console.log('成功')
          wx.showLoading({title: '连接中...'})
          wx.connectWifi({
            SSID: this.msg.wifiName,
            password: this.msg.wifiPassword,
            success: (res) =>{
              console.log(res)
              wx.hideLoading()
              setTimeout(() => {
                that.$toast('连接成功~')
              }, 500);
            },
            fail: (err) =>{
              console.log(err)
              setTimeout(() => {
                that.$toast('连接失败~')
              }, 500);
              wx.hideLoading()
            }
          });
        },
        fail: (res) =>{
          that.$toast('连接失败~')
        }
      });
    },

    // 房间图片预览
    previewImage(img) {
      wx.previewImage({
        current: img[0], // 当前显示图片的http链接
        urls: img, // 需要预览的图片http链接列表
      });
    },

    // 获取订单详情
    getOrderMsg(){
      this.$showLoading('加载中...')
      getMyOrderDetails({orderId:this.orderId}).then(res=>{
        if(res.statusCode == '00000'){
          let weeks = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
          let startTime = res.data.startTime.replace(/-/g,'/')
          let endTime = res.data.startTime.replace(/-/g,'/')
          startTime =  startTime.replace(/-/g,'/')
          endTime =  endTime.replace(/-/g,'/')
          let startDay = new Date(startTime)
          let endDay = new Date(endTime)
          let startWeek = startDay.getDay()
          let endWeek = endDay.getDay()
          let startDate1 = res.data.startTime.split(" ")[0];
          let startSj = res.data.startTime.split(" ")[1].split(":");
          let endDate1 = res.data.endTime.split(" ")[0];
          let endSj = res.data.endTime.split(" ")[1].split(":");
          let timeLength = this.getHour(res.data.startTime,res.data.endTime)
          // console.log(weeks[startWeek])
          let data = {
            startDate1,
            startSj:`${startSj[0]}:${startSj[1]}`,
            endDate1,
            endSj:`${endSj[0]}:${endSj[1]}`,
            startWeek:weeks[+startWeek],
            endWeek:weeks[+endWeek],
            timeLength,
          }
          console.log(data)
          this.msg = Object.assign(data,res.data)
          wx.hideLoading()
        }else{
          wx.hideLoading()
          this.$toast(res.message)
        }
      })
    },

    // 算选择多少小时
    getHour(s1, s2) {
      var reDate = /\d{4}-\d{1,2}-\d{1,2} /;
      s1 = new Date((reDate.test(s1) ? s1 : '2018-1-1 ' + s1).replace(/-/g, '/'));
      s2 = new Date((reDate.test(s2) ? s2 : '2018-1-1 ' + s2).replace(/-/g, '/'));
      var ms = s2.getTime() - s1.getTime();
      if (ms < 0) return 0;
      return (ms / 1000 / 60 / 60).toFixed(1);  //小时
    },

    onChange(e) {
      this.timeData = e.target
      this.timeData.hours = this.timeData.hours<10?'0'+this.timeData.hours:this.timeData.hours
      this.timeData.minutes = this.timeData.minutes<10?'0'+this.timeData.minutes:this.timeData.minutes
      this.timeData.seconds = this.timeData.seconds<10?'0'+this.timeData.seconds:this.timeData.seconds
    },

    onChange1(e) {
      this.timeData1 = e.target
      this.timeData1.hours = this.timeData1.hours<10?'0'+this.timeData1.hours:this.timeData1.hours
      this.timeData1.minutes = this.timeData1.minutes<10?'0'+this.timeData1.minutes:this.timeData1.minutes
      this.timeData1.seconds = this.timeData1.seconds<10?'0'+this.timeData1.seconds:this.timeData1.seconds
    },
  },
  onLoad(options) {
    console.log(options)
    this.orderId = options.orderId
    if(options.shareType){
      this.shareType = options.shareType
    }else{
      this.shareType = 0
    }
    if(!getToken()){
      wx.login({
        success:(res)=>{
          let code = res.code
          this.$store.dispatch("userLogin", code).then(res=>{
            if(res.statusCode == '00000'){
              this.getOrderMsg()
            }
          })
        }
      })
    }else{
      this.getOrderMsg()
    }
    wx.getSystemInfo({
      success: (res) => {
        console.log("手机信息res" + res.model);
        let modelmes = res.model;
        if (
          modelmes.search("iPhone 14") != -1 ||
          modelmes.search("iPhone 13") != -1 ||
          modelmes.search("iPhone 12") != -1 ||
          modelmes.search("iPhone 11") != -1 ||
          modelmes.search("iPhone X") != -1 ||
          modelmes.search("iPhone XR") != -1 ||
          modelmes.search("iPhone XS") != -1
        ) {
          this.isIphoneXnum = 30;
        } else {
          this.isIphoneXnum = 20;
        }
      },
    });
  },
};
</script>

<style lang="scss" scoped>
.content_box {
  min-height: 100vh;
  background: #f0f0f0;
  .time_box{
    padding:0 30rpx;
    height: 84rpx;
    background: #f8f2e2;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .box{
      display: flex;
      align-items: center;
      font-size:30rpx;
      color:#8d6a41;
      .down{
        margin-left:20rpx;
        font-weight: bold;
        .item{
          font-size:30rpx;
          color:#8d6a41;
        }
      }
    }
  }
  .img_box{
    position: relative;
    .dots{
      position: absolute;
      bottom: 30rpx;
      right: 30rpx;
      width: 70rpx;
      height: 46rpx;
      background: rgba(0, 0, 0, 0.4);
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 20rpx;
      font-size: 28rpx;
      img{
        width: 30rpx;
        margin-right: 5rpx;
      }
    }
  }
  .room_msg{
    margin: 26rpx;
    background: #fff;
    padding:0 26rpx 30rpx 26rpx;
    .name_box{
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: bold;
      font-size:32rpx;
      height: 94rpx;
      border-bottom:1px solid #f7f7f7;
      img{
        width: 40rpx;
        height: 40rpx;
      }
    }
    .msg_box{
      background: #fff;
      margin:0 auto;
      border-radius: 15rpx;
      margin-top:30rpx;
      .changeTime{
        border-radius: 15rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .text{
          font-size:28rpx;
          color:#000;
          margin-bottom:20rpx;
        }
        .time{
          font-size:32rpx;
          font-weight: bold;
          margin-bottom:20rpx;
        }
        .day{
          font-size:28rpx;
        }
        .center{
          display: flex;
          align-items: center;
          .totel{
            width: 180rpx;
            height: 62rpx;
            line-height: 62rpx;
            background: linear-gradient(to right, #2e3341 50%,#4f5363 100%);
            text-align: center;
            border-radius: 100rpx;
            color:#fff;
            font-size:28rpx;
          }
        }
      }
    }
    button::after {
      border: none;
    }
    button{
      background: none;
      margin:0;
      padding:0
    }
  }
  .cz_box{
    margin:0 26rpx;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: space-around;
    height: 150rpx;
    text-align: center;
    font-size:26rpx;
    img{
      width: 44rpx;
      height: 44rpx;
      margin-bottom:10rpx;
    }
  }
  .order_msg{
    margin:26rpx;
    background: #fff;
    .title_box{
      height: 102rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom:1px solid #f9f9f9;
      padding:0 26rpx;
      .title{
        color:#222;
        font-weight: bold;
        font-size:30rpx; 
      }
      .status{
        padding:0 10rpx;
        height: 42rpx;
        line-height: 42rpx;
        text-align: center;
        background: #92b46c;
        font-size:26rpx;
        color:#fff;
        border-radius: 30rpx;
        border-bottom-left-radius: 0;
      }
    }
    .list_box{
      padding:0 26rpx 26rpx 26rpx;
      margin-top:26rpx;
      .box{
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom:40rpx;
        font-size:28rpx;
        color:#999999;
        font-weight: 500;
        &:last-child{
          margin-bottom:0;
        }
        .text{
          color:#646464;
        }
      }
    }
  }
  .button_box{
    margin:0 26rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    p{
      width: 48%;
      height: 90rpx;
      line-height: 90rpx;
      text-align: center;
      background: #fff;
      border:1px solid #222222;
      color:#222;
      border-radius: 6rpx;
      font-size:30rpx;
    }    
    .xd{
      background: #222;
      color:#fff;
    }
  }

  .wifi_pop{
    /deep/ .van-popup {
      background: none;
      width: 84%;
      padding-bottom:100rpx;
    }
    .box{
      height: 632rpx;
      position: relative;
      .bj{
        width: 100%;
        height: 100%;
        top:0;
        left: 0;
        position: absolute;
      }
      .nr{
        position: relative;
        z-index: 10;
        width: 90%;
        margin:0 auto;
        .title{
          padding-top:140rpx;
          color:#000;
          font-size:40rpx;
          font-weight: bold;
          margin-bottom:12rpx;
        }
        .text{
          font-size:26rpx;
          color:#000;
        }
        .zhanghao{
          padding:48rpx;
          background: #fff;
          margin-top:44rpx;
          color:#222222;
          font-size:28rpx;
          p{
            &:nth-of-type(1){
              margin-bottom:24rpx;
            }
          }
        }
        .anniu{
          width: 100%;
          height: 80rpx;
          background: #222222;
          text-align: center;
          line-height: 80rpx;
          color:#fff;
          font-size:28rpx;
          margin-top:24rpx;
          border-radius: 4rpx;
        }
      }
    }
    .close{
      width: 64rpx;
      height: 64rpx;
      border:4rpx solid #fff;
      border-radius: 50%;
      margin:32rpx auto 0 auto;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size:46rpx;
      color:#fff;
    }
  }
  .kefu_pop{
    /deep/ .van-popup {
      border-top-right-radius: 20rpx !important;
      border-top-left-radius: 20rpx !important;
    }
    .title{
      height: 120rpx;
      line-height: 120rpx;
      font-size:34rpx;
      color:#505050;
      font-weight: 600;
      text-align: center;
    }
    .nr{
      display: flex;
      align-items: center;
      justify-content: space-around;
      padding-bottom:48rpx;
    }
    button::after {
      border: none;
    }
    button{
      background: none;
      color:#222;
      margin:0;
      .img{
        width: 100rpx;
        height: 100rpx;
        background: #F9F9FB;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        img{
          width: 52rpx;
          height: 52rpx;
        }
      }
      .text{
        color:#6C6C6C;
        font-size:24rpx;
        text-align: center;
      }
    }
    .quxiao{
      margin:0 30rpx;
      height: 96rpx;
      line-height: 96rpx;
      background: #222;
      border-radius: 4rpx;
      margin-bottom:24rpx;
      text-align: center;
      font-size:30rpx;
      color:#fff;
    }
  }
}
</style>